package com.project.controller;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import util.BaseImg64;
import util.GoogleCompress;

import java.io.File;
import java.io.IOException;

/**
 * @author lyl
 * description:服务器1controller
 */
@RestController
@RequestMapping
public class PicController {
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 设置回调方法
     */
    RabbitTemplate.ConfirmCallback callback = (CorrelationData correlationData, boolean b, String s) -> {
        System.out.println("已经进入队列,进入回调方法");
        if (b) {
            System.out.println("生产者投递成功");
            //删除源文件
            String fi = correlationData.getId();
            File f = new File(fi);
            if (f.exists()) {
                System.out.println("删除源文件");
                //删除源文件
                f.delete();
            }
        } else {
            System.out.println("投递失败");
        }
    };

    /**
     * 服务器1获取从用户传递上的文件
     *
     * @param file
     * @return fileName
     */
    @PostMapping("uploadImg")
    private void uploadIng(@RequestParam("file") MultipartFile file) {
        //开启手动确认
        rabbitTemplate.setMandatory(true);//开启消息确认
        //绑定回调函数
        rabbitTemplate.setConfirmCallback(callback);

        //得到上传文件名
        String fileName = file.getOriginalFilename();
        //将文件名以时间毫秒数重命名
        fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        File f = new File("e:/img2/" + fileName);
        try {
            //将文件上传至指定位置
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件上传之后进行压缩操作,覆盖原有图片
        GoogleCompress.googleCompress("e:/img2/" + fileName, "e:/img2/" + fileName);
        //将图片转换为base64字符串
        String str = BaseImg64.getImageStrFromPath("e:/img2/" + fileName);
        CorrelationData correlationData = new CorrelationData("e:/img2/" + fileName);
        rabbitTemplate.convertAndSend("picExchange", "trance.pic", str, correlationData);
    }
}
